//
//  DownLoadManager.m
//  Ting
//
//  Created by 安静的美男子 on 14/11/28.
//  Copyright (c) 2014年 安静的美男子. All rights reserved.
//

#import "DownLoadManager.h"
static DownLoadManager *shareManager = nil;

@implementation DownLoadManager

+(DownLoadManager *)shareManager
{
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            shareManager  = [[DownLoadManager alloc]init];
            
        });
        return shareManager;
    
}
-(void)downloadWithBlock:(myBlock)block url:(NSString *)urlString name:(NSString *)name
{
    NSString * webPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Private Documents/Temp"];
    NSString * cachePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Private Documents/Cache"];
    NSLog(@"%@", webPath);
    //创建文件管理
    NSFileManager * fileManager = [NSFileManager defaultManager];
    //判断是否存在文件路径 没有则创建 临时文件  下载文件
    if(![fileManager fileExistsAtPath:webPath])
    {
        [fileManager createDirectoryAtPath:webPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    if (![fileManager fileExistsAtPath:cachePath]) {
        [fileManager createDirectoryAtPath:cachePath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    //拼接文件路径 判断下载文件是下载完成 或正在下载
    if ([fileManager fileExistsAtPath:[cachePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp3",name]]]) {
        block(YES);
    }
    else if([fileManager fileExistsAtPath:[webPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp3",name]]])
    {
        block(YES);
    }
    //否则下载
    else
    {
        shareManager.webPath = webPath;
        shareManager.url = urlString;
        shareManager.tempFile = [webPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp3",name]];
        _request = [[ASIHTTPRequest alloc] initWithURL:[NSURL URLWithString:urlString]];
        [_request setDownloadDestinationPath:[cachePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp3",name]]];
        [_request setTemporaryFileDownloadPath:[webPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.mp3",name]]];
        [_request setDelegate:self];
        //获取文件总大小  每次下载大小
        [_request setBytesReceivedBlock:^(unsigned long long size, unsigned long long total) {
            NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
            [user setDouble:total forKey:@"file_length"];
            shareManager.size = size;
            shareManager.total = total;
        }];
        
        //_request.downloadProgressDelegate = sharedManager.myProgressView;
        [_request setAllowResumeForFileDownloads:YES];
        [_request startAsynchronous];
        block(NO);
    }
    
    

}
-(void)requestFaild:(ASIHTTPRequest *)request
{
    NSError *error = [request error];
    NSLog(@"%@",error);
    
}
@end
